/**
 * 基于Antd的上传组件
 * @author SPY
 * @description 用于图片、附件上传等等
 * @date 2020/03/09
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'loadsh';
import { Upload, Button, Icon, message } from 'antd';

class SimpleUpload extends Component {

    // 定义传入属性
    static propTypes = {
        fileIdKey: PropTypes.string,  // 文件主键对应的id名称
        fileNameKey: PropTypes.string, // 文件对应的name名称

        maxUploadCount: PropTypes.number, // 上传文件的个数,默认为0：表示不限制
        downloadOnly: PropTypes.bool, // 是否只允许下载，不允许上传和删除
        isDrag: PropTypes.bool, // 是否支持拖动上传

        onFileChange: PropTypes.func, // 文件发生变化时的回调函数
        defaultFileList: PropTypes.array, // 默认的文件列表
    }

    // 定义传入属性的默认值
    static defaultProps = {
        fileIdKey: 'uid',
        fileNameKey: 'name',

        maxUploadCount: 0,
        downloadOnly: false,
        isDrag: true,
        onFileChange: () => { },
        defaultFileList: [],
    }

    state = {
        fileList: [],
    }

    componentDidMount() {
        this.fetchDefaultFileList();
    }

    componentWillReceiveProps(props) {
        this.fetchDefaultFileList(props);
    }

    // 处理默认列表
    fetchDefaultFileList = (props) => {
        const { defaultFileList } = props || this.props;
        const { fileList } = this.state;
        if (!_.isEqual(defaultFileList, fileList)) {
            this.setState({
                fileList: _.uniq([...fileList, ...defaultFileList]),
            });
        }
    }

    // 文件发生改变，回调给父组件
    notifyFileListChange = () => {
        const { onFileChange } = this.props;
        const { fileList } = this.state;
        if (typeof onFileChange === 'function') onFileChange(fileList);
    }

    // 移除文件
    onFileRemove = (file) => {
        this.setState(state => {
            const index = state.fileList.indexOf(file);
            const newFileList = state.fileList.slice();
            newFileList.splice(index, 1);
            return {
                fileList: newFileList,
            };
        }, this.notifyFileListChange);
        // return false;
    }

    // 下载文件
    onFileDownload = (file) => {
        const { fileIdKey, fileNameKey } = this.props;
        const fileId = file[fileIdKey];
        const fileName = file[fileNameKey];

        const xhr = new XMLHttpRequest();
        // 设置请求方式及url
        xhr.open('GET', '/api/ib/');
        // 设置请求头参数，携带token
        xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`);
        // 设置响应类型
        xhr.responseType = 'blob';
        // 
        xhr.onload = function (e) {
            if (this.status === 200) {
                // 请求成功
                const blob = this.response;
                // 创建a标签
                const a = document.createElement('a');
                // 创建url
                const url = URL.createObjectURL(blob);

                a.href = url;
                // 设置文件的名称
                a.download = fileName;
                a.click();
                // 释放之前创建的URL对象
                window.URL.revokeObjectURL(url);
            }
        };
        // 发送请求
        xhr.send();
    }

    // 文件上传之前触发的回调函数
    onBeforeUpload = (file) => {
        const { maxUploadCount } = this.props;
        const { fileList } = this.state;
        const bool = maxUploadCount > 0 && fileList.length >= maxUploadCount;
        if (bool) {
            message.info(`上传失败：文件最多上传 ${maxUploadCount} 个`);
            return;
        }
        this.setState(state => ({
            fileList: [...state.fileList, file],
        }), this.notifyFileListChange);
        // return false;
    }

    renderUploadPage = () => {
        const { fileList } = this.state;
        const { isDrag, maxUploadCount, downloadOnly } = this.props;
        if (downloadOnly) return null;
        if (isDrag) {
            return (
                <div>
                    <p className="ant-upload-drag-icon">
                        <Icon type="inbox" />
                    </p>
                    <p className="ant-upload-text">上传文件</p>
                    <p className="ant-upload-hint">
                        支持点击或者拖动上传
                    </p>
                </div>
            )
        }
        const disabled = maxUploadCount > 0 && fileList.length >= maxUploadCount;
        return (
            <div>
                <Button icon='upload' disabled={disabled}>上传文件</Button>
            </div>
        )
    }

    // handleUpload = () => {
    //     const { fileList } = this.state;
    //     const formData = new FormData();
    //     fileList.forEach(file => {
    //         formData.append('files[]', file);
    //     });

    //     reqwest({
    //         url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    //         method: 'post',
    //         processData: false,
    //         data: formData,
    //         success: () => {
    //             this.setState({
    //                 fileList: [],
    //             });
    //         },
    //         error: () => {
    //         },
    //     });
    // };

    render() {
        const { fileList } = this.state;
        const { isDrag, downloadOnly } = this.props;

        const Ud = isDrag && !downloadOnly ? Upload.Dragger : Upload;

        return (
            <Ud
                onRemove={this.onFileRemove}
                onDownload={this.onFileDownload}
                beforeUpload={this.onBeforeUpload}
                fileList={fileList}
                showUploadList={{
                    showPreviewIcon: true,
                    showRemoveIcon: true,
                    showDownloadIcon: false,
                }}
            >
                {this.renderUploadPage()}
            </Ud>
        )
    }
}


export default SimpleUpload;